path = require 'path'
exec = require('child_process').exec
Promise = require 'bluebird'
pExec = Promise.promisify exec
_ = require 'lodash'
co = require 'co'

config = require '../config'
log = require '../log'
fileUtil = require '../fileUtil'

EntityService = require './EntityService'

# 异步处理
exports.processThumbnailFieldAsync = (ctx, entityName, fieldName, _id, fieldValue)->
    co(-> yield from exports.gProcessThumbnailField(ctx, entityName, fieldName, _id, fieldValue)).catch (e)->
        log.system.error e, 'processThumbnailField'

exports.gProcessThumbnailField = (ctx, entityName, fieldName, _id, fieldValue)->
    return unless fieldValue

    if _.isArray fieldValue
        for image in fieldValue when image?
            image.thumbnail = yield from gThumbnail image?.path
    else
        fieldValue.thumbnail = yield from gThumbnail fieldValue.path

    change = {$set: {}}
    change.$set[fieldName] = fieldValue
    yield from EntityService.gNativeUpdateMongoById ctx, entityName, _id, change

gThumbnail = (imagePath)->
    return null unless imagePath

    ext = path.extname imagePath
    basename = path.basename imagePath, ext

    dir = path.dirname imagePath
    thumbnailRelativePath = path.join(dir, basename + ".thumb" + ext)

    srcFullPath = path.join config.fileDir, imagePath
    targetFullPath = path.join config.fileDir, thumbnailRelativePath

    unless yield from fileUtil.gFileExists(targetFullPath)
        thumbnailSize = config.articleThumbnailSize
        cmd = "convert #{srcFullPath} -resize #{thumbnailSize}x#{thumbnailSize}\\> #{targetFullPath}"

        try
            yield pExec cmd
        catch e
            log.system.error e, 'gThumbnail execute cmd'

    thumbnailRelativePath


